package com.yq.wiki.service;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yq.wiki.mapper.CategoryMapper;
import com.yq.wiki.domain.Category;
import com.yq.wiki.domain.CategoryExample;
import com.yq.wiki.req.CategoryQueryReq;
import com.yq.wiki.req.CategorySaveReq;
import com.yq.wiki.resp.CategoryQueryResp;
import com.yq.wiki.resp.PageResp;
import com.yq.wiki.util.CopyUtil;
import com.yq.wiki.util.SnowFlake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class CategoryService {

    public static final Logger LOG = LoggerFactory.getLogger(CategoryService.class);
    @Resource
    CategoryMapper categoryMapper;

    @Resource
    SnowFlake snowFlake;


    public List<CategoryQueryResp> all(){
        CategoryExample categoryExample = new CategoryExample();
        //按顺序排序
        categoryExample.setOrderByClause("sort asc");
        List<Category> categorysList = categoryMapper.selectByExample(categoryExample);

        //列表复制
        List<CategoryQueryResp> list = CopyUtil.copyList(categorysList, CategoryQueryResp.class);
        return list;
    }

    public PageResp<CategoryQueryResp> list(CategoryQueryReq req){
        PageHelper.startPage(req.getPage(),req.getSize());
        CategoryExample categoryExample = new CategoryExample();
        categoryExample.setOrderByClause("sort asc");
        CategoryExample.Criteria criteria = categoryExample.createCriteria();
        List<Category> categorysList = categoryMapper.selectByExample(categoryExample);

        PageInfo<Category> pageInfo = new PageInfo<>(categorysList);
        LOG.info("总行数:{}",pageInfo.getTotal());
        LOG.info("总页数:{}",pageInfo.getPages());

        List<CategoryQueryResp> list = CopyUtil.copyList(categorysList, CategoryQueryResp.class);

        PageResp<CategoryQueryResp> pageResp = new PageResp();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(list);
        return pageResp;
    }



    /**
     * 保存
     */
    public void save(CategorySaveReq req){
        Category category = CopyUtil.copy(req, Category.class);
        //要判断是否为新增还是更新  ，通过request的id查看
        if (ObjectUtils.isEmpty(req.getId())){
            //新增  通过雪花算法生成id
            category.setId(snowFlake.nextId());
            System.out.println("新增数据的id"+category.getId());
            categoryMapper.insert(category);
        }else {
            //更新
            categoryMapper.updateByPrimaryKey(category);
        }
    }

    public void delete(Long id){
        categoryMapper.deleteByPrimaryKey(id);
    }
}
